

import com.google.common.collect.Lists;

import org.apache.commons.io.FileUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;

public class VelocityUtils {
    /**
     * 分页
     *
     * @param bodyList 数据集合
     * @param pageSize 页码
     * @return 模板数据
     */
    public static List<List<Map<String, Object>>> paging(List<Map<String, Object>> bodyList, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        int num = bodyList.size() / pageSize;
        List<List<Map<String, Object>>> pagingList = Lists.partition(bodyList, num);

        return pagingList;
    }

    /**
     *
     * @param head
     * @param pagingList
     * @throws IOException
     */
    public static void velocityTemplate(Map<String,Object> head,List<List<Map<String, Object>>> pagingList) throws IOException {
        VelocityEngine engine = new VelocityEngine();
        Properties p = new Properties();
        p.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
        p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        engine.init(p);
        //获取模板
        Template template = engine.getTemplate("velocity.vm");
        VelocityContext vc = new VelocityContext();

        List<Map<String, Object>> headList = new ArrayList<>();

        vc.put("head", head);
        vc.put("pageList", pagingList);

        StringWriter sw = new StringWriter();
        template.merge(vc, sw);
        String localPath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "vm.java";
//            System.out.println(localPath);
        FileUtils.writeStringToFile(new File(localPath), sw.toString(), "UTF-8");
    }

}
